package com.superboo.core.controller;

import com.superboo.core.dao.PersonRepository;
import com.superboo.core.domain.Person;
import com.superboo.core.domain.Result;
import com.superboo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;

/**
 * PersonController
 *
 * @author peiran zhang
 * @date 2017/4/14
 */
@RequestMapping("person")
@RestController
public class PersonController {

    @Autowired
    PersonRepository personRepository;

    /**
     * 保存
     * save支持批量保存：<S extends T> Iterable<S> save(Iterable<S> entities);
     *
     * 删除：
     * 删除支持使用id，对象以，批量删除及删除全部：
     * void delete(ID id);
     * void delete(T entity);
     * void delete(Iterable<? extends T> entities);
     * void deleteAll();
     *
     */
    @PostMapping("/save")
    public Result<Person> save(@Valid Person person, BindingResult bindingResult) {

        //验证是否有错误
        if (bindingResult.hasErrors()) {
            return ResultUtil.validationError(bindingResult.getFieldError().getDefaultMessage());
        }

        return ResultUtil.success(personRepository.save(person));
    }

    /**
     * 根据名称返回人
     * @param name
     * @return
     */
    @GetMapping("/q1/{name}")
    public Object q1 (@PathVariable String name){
        return personRepository.findByName(name);
    }

    /**
     * 根据name和address返回一个人
     * @param name
     * @param address
     * @return
     */
    @GetMapping("/q2")
    public Person q2 (String name,String address){
        return personRepository.findByNameAndAddress(name,address);
    }

    /**
     * 测试withNameAndAddressQuery
     */
    @GetMapping("/q3")
    public Person q3(String name,String address){
        return personRepository.withNameAndAddressQuery(name, address);
    }

    /**
     * 测试withNameAndAddressNamedQuery
     */
    @GetMapping("/q4")
    public Person q4(String name,String address){
        return  personRepository.withNameAndAddressNamedQuery(name, address);
    }

    /**
     * 测试排序
     */
    @GetMapping("/sort")
    public List<Person> sort(){
        return  personRepository.findAll(new Sort(Sort.Direction.ASC,"age"));
    }

    /**
     * 测试分页
     */
    @GetMapping("/page")
    public Page<Person> page(){
        Page<Person> pagePeople = personRepository.findAll(new PageRequest(1, 2));
        return pagePeople;
    }

}

